//
// Created by Shith on 2016/9/25.
//

#include <iostream>
#include "Executor.h"
#include "ActMaker/ActMaker.h"
#include "thirdparty/cmdline.h"

#include <memory>
#include "LogicExecutor.h"

using std::cout;



Executor::Executor(int Argc, char *Argv[]): argc(Argc), argv(Argv)
{
#ifdef _SERVER_
	ld = new Loader_web(lgc);
	//jgm = new Judgement_web(lgc);
#else
	//ld = new Loader_local(lgc);
	//jgm = new Judgement_local(lgc);
#endif
}

Executor::~Executor()
{
}

void Executor::judge(bool loadAiFromArgv)
{
	int round=0;
	int winner;
    cmdline::parser command;
	command.add<int> ("round", 'r', "number of rounds", false, MAX_ROUND);//add<类型>(全称，简写，描述，是否可省略，若省略的默认参数)
	command.parse_check (argc, argv);
	//lgc->init();
	int input_round = command.get<int> ("round");
	std::vector<std::string> rest = command.rest();//rest[0]是exe，rest[1]和nake[2]分别是两个dll
    LogicExecutor logicExecutor;
	if(loadAiFromArgv)
	{
		logicExecutor.act[0] = std::make_shared<AiActMaker>(rest[0].c_str());
		logicExecutor.act[1] = std::make_shared<AiActMaker>(rest[1].c_str());
		// logicExecutor.act[0] = std::make_shared<AiActMaker>("Ai/libsthAi.dll");
		// logicExecutor.act[1] = std::make_shared<AiActMaker>("Ai/libdecentAi0.dll");
	}
    do
    {
		cout << "Round:" << (round++) << "\n";
        logicExecutor.fetchCommands(1);
        logicExecutor.fetchCommands(2);
        winner = logicExecutor.oneRoundRun();
        if (round == input_round)
            break;
    }
    while (winner == Game::UNFINISHED);
    logicExecutor.game->dumpReplay("replay");
    if (winner == Game::TIE)
        cout << "The score is tied. No Winner." << "\n";
    else
        cout << "winner:" << winner << "\n";

#ifdef _SERVER_
	try
	{
		logic::kill(0);
		logic::kill(1);
		logic::kill(2);
	}
	catch(...)
	{
	}
	try{
		logic::end([](int,SocketBase&){});
	}
	catch(...){}
#endif//_SERVER_
}
